package BackTrack.Medium;

import java.util.*;

public class LC0046 {
    int N;
    int[] nums;
    ArrayList<List<Integer>> result = new ArrayList<>();
    boolean[] picked;

    public List<List<Integer>> permute(int[] nums) {
        this.nums = nums;
        N = nums.length;
        picked = new boolean[nums.length];
        LinkedList<Integer> path = new LinkedList<>();

        innerRecursive(path);

        return result;
    }

    private void innerRecursive(LinkedList<Integer> path) {
        for (int i = 0; i < nums.length; i++) {
            if (picked[i]) continue;
            path.addLast(nums[i]);
            if (path.size() == N) result.add(new LinkedList<>(path));
            else {
                picked[i] = true;
                innerRecursive(path);
                picked[i] = false;
            }
            path.removeLast();
        }
    }
}
